package com.uchedao.vehicledetection.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.uchedao.mybaselibrary.utils.ImageUtils;
import com.uchedao.mybaselibrary.view.dialog_for_ios.ZAlertDialog;
import com.uchedao.vehicledetection.R;
import com.uchedao.vehicledetection.global.GlobalInfo;
import com.uchedao.vehicledetection.model.Skeleton;
import com.uchedao.vehicledetection.utils.Util;
import com.uchedao.vehicledetection.view.widget.BadgeView;
import com.uchedao.vehicledetection.view.widget.stickylistheaders.StickyListHeadersAdapter;

public class SkeletonAdapter extends BaseAdapter implements StickyListHeadersAdapter {
    private Skeleton[] skeletons;
    private LayoutInflater inflater;
    private SkeletonAdapterListener listener;
    private int resultTvWidth;
    private String[] values;
    private Context mContext;

    public interface SkeletonAdapterListener {
        /**
         * 图片添加
         *
         * @param skeleton
         */
        void onPhotoAdd(Skeleton skeleton);

        /**
         * 图片修改
         *
         * @param skeleton
         */
        void onPhotoEdit(Skeleton skeleton);
    }

    public SkeletonAdapter(Context act, Skeleton[] skeletons, SkeletonAdapterListener skeletonAdapterListener) {
        inflater = LayoutInflater.from(act);
        this.skeletons = skeletons;
        mContext = act;
        listener = skeletonAdapterListener;
        values = GlobalInfo.resources.getStringArray(R.array.skeleton_value_entries);
    }

    @Override
    public int getCount() {
        return skeletons.length;
    }

    @Override
    public Object getItem(int position) {
        return skeletons[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        TextView titleTv;
        TextView valueTv;
        LinearLayout photoContainer;
        View gapView;
        FrameLayout photoFl;
        ImageView photoIv;
        BadgeView badge;
        ImageView photoAddIv;
    }

    private OnClickListener photoAddListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onPhotoAdd((Skeleton) v.getTag());
        }
    };
    private OnClickListener resultListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            final Skeleton skeleton = (Skeleton) v.getTag();

            showAlertDialog(skeleton.name, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //如果原先有异常图片，又选择了未见事故修复，则弹出提示对话框
                    if (which == 0 && skeleton.pic_path_list.size() > 0) {
                        AlertDialog alert = new ZAlertDialog.Builder(mContext).setTitle(R.string.prompt)
                                .setMessage(R.string.lose_photo_message).setNegativeButton(R.string.cancel, null)
                                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        skeleton.result = 0;
                                        skeleton.pic_path_list.clear();
                                        notifyDataSetChanged();
                                    }
                                }).create();
                        alert.show();

                    } else {
                        skeleton.result = which;
                        notifyDataSetChanged();
                    }

                }
            });
        }
    };

    /**
     * 显示对话框
     *
     * @param title
     * @param listener
     */
    private void showAlertDialog(String title, DialogInterface.OnClickListener listener) {
        AlertDialog alert = new AlertDialog.Builder(mContext).setTitle(title)
                .setItems(R.array.skeleton_value_entries, listener).create();
        alert.show();
    }

    private OnClickListener editPicListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (listener != null)
                listener.onPhotoEdit((Skeleton) v.getTag());
        }

    };

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_accident_skeleton, null);
            convertView.setTag(viewHolder);
            viewHolder.titleTv = (TextView) convertView.findViewById(R.id.skeleton_item_title_tv);
            viewHolder.valueTv = (TextView) convertView.findViewById(R.id.skeleton_item_result_tv);
            viewHolder.photoContainer = (LinearLayout) convertView.findViewById(R.id.skeleton_item_photo_container);
            viewHolder.photoFl = (FrameLayout) convertView.findViewById(R.id.skeleton_item_photo_fl);
            viewHolder.photoIv = (ImageView) convertView.findViewById(R.id.skeleton_item_photo_iv);
            viewHolder.badge = new BadgeView(mContext);
            viewHolder.badge.setBackground(9, GlobalInfo.resources.getColor(R.color.deep_red));
            viewHolder.badge.setTargetView(viewHolder.photoFl);

            viewHolder.badge.setBadgeMargin(4);
            viewHolder.photoAddIv = (ImageView) convertView.findViewById(R.id.skeleton_item_add_photo_iv);
            viewHolder.valueTv.setMinWidth(resultTvWidth);
            viewHolder.valueTv.setOnClickListener(resultListener);
            viewHolder.photoContainer.setOnClickListener(photoAddListener);
            viewHolder.photoIv.setOnClickListener(editPicListener);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        Skeleton skeleton = skeletons[position];
        viewHolder.photoContainer.setTag(skeleton);
        viewHolder.photoAddIv.setTag(skeleton);
        viewHolder.photoIv.setTag(skeleton);

        if (skeleton.pic_path_list.size() > 0) {
            viewHolder.photoFl.setVisibility(View.VISIBLE);
//            viewHolder.photoIv.setImageBitmap(Util.getimage(skeleton.pic_path_list.get(0), 300, 300));
            ImageUtils.loadImage(Util.getSDcardImageUrl(skeleton.pic_path_list.get(0)), viewHolder.photoIv, R.mipmap.ic_launcher);

        } else {
            viewHolder.photoFl.setVisibility(View.GONE);
        }
        viewHolder.badge.setBadgeCount(skeleton.pic_path_list.size());

        viewHolder.titleTv.setText(skeleton.name);
        viewHolder.valueTv.setTag(skeleton);
        viewHolder.valueTv.setText(values[skeleton.result]);
        if (skeleton.result == 0) {// 正常
            viewHolder.photoAddIv.setVisibility(View.INVISIBLE);
            viewHolder.valueTv.setBackgroundResource(R.color.deep_green);
            viewHolder.valueTv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_blue_yes, 0,
                    R.mipmap.ic_drop_arrow, 0);
        } else {
            viewHolder.photoAddIv.setVisibility(View.VISIBLE);
            viewHolder.valueTv.setBackgroundResource(R.color.deep_red);
            viewHolder.valueTv.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_red_cross, 0,
                    R.mipmap.ic_drop_arrow, 0);
        }

        return convertView;
    }

    class HeaderViewHolder {
        // TextView imageTv;
//		ImageView showDetail;
        TextView title;
    }

//	private OnClickListener showDetailListener = new OnClickListener() {
//
//		@Override
//		public void onClick(View v) {
//			String header = (String) v.getTag();
//			 ArrayList<Integer> imgIds = new ArrayList<Integer>();
//			 imgIds.add(R.mipmap.pad_bg);
//			 for (Skeleton skeleton : skeletons) {
//			 if (skeleton.header.equals(header)) {
//			 if (skeleton.result == 0) {
//			 imgIds.add(getDrawableResId("pad_" + skeleton.number
//			 + "_a"));
//			 } else {
//			 imgIds.add(getDrawableResId("pad_" + skeleton.number
//			 + "_b"));
//			 }
//			 }
//			 }
//			 showDetailImageView(imgIds);
//
//			final Dialog dialog = new Dialog(mContext);
//			// ImageView imageView = new ImageView(mContext);
//			ImageView imageView = CoverImageUtil.getSkeletonCoverImageView(mContext, header, skeletons);
//			imageView.setPadding(100, 100, 100, 100);
//
//			imageView.setOnClickListener(new OnClickListener() {
//
//				@Override
//				public void onClick(View v) {
//					dialog.dismiss();
//				}
//			});
//			dialog.setCanceledOnTouchOutside(true);
//			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
//			dialog.setContentView(imageView);
//			dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
//			dialog.show();
//
//		}
//	};

    // /**
    // * 显示详情图片
    // *
    // * @param imgIds
    // */
    // private void showDetailImageView(ArrayList<Integer> imgIds) {
    // Drawable[] drawables = new Drawable[imgIds.size()];
    // for (int i = 0; i < drawables.length; i++) {
    // drawables[i] = GlobalInfo.resources.getDrawable(imgIds.get(i));
    // }
    // LayerDrawable layerDrawable = new LayerDrawable(drawables);
    //
    // final Dialog dialog = new Dialog(mContext);
    // ImageView imageView = new ImageView(mContext);
    // imageView.setImageDrawable(layerDrawable);
    // imageView.setPadding(100, 100, 100, 100);
    //
    // imageView.setOnClickListener(new OnClickListener() {
    //
    // @Override
    // public void onClick(View v) {
    // dialog.dismiss();
    // }
    // });
    // dialog.setCanceledOnTouchOutside(true);
    // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // dialog.setContentView(imageView);
    // dialog.getWindow().setBackgroundDrawableResource(
    // android.R.color.transparent);
    // dialog.show();
    // }

    /**
     * 根据名称得到ID
     *
     * @param name
     * @return
     */
    private int getDrawableResId(String name) {
        return GlobalInfo.resources.getIdentifier(name, "drawable", mContext.getPackageName());
    }

    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new HeaderViewHolder();
            convertView = inflater.inflate(R.layout.item_accident_skeleton_subject, null);
            convertView.setTag(viewHolder);
            viewHolder.title = (TextView) convertView.findViewById(R.id.skeleton_subject_name_tv);
//			viewHolder.showDetail = (ImageView) convertView.findViewById(R.id.skeleton_subject_show_iv);

            // viewHolder.result.setMinWidth(resultTvWidth);
//			viewHolder.showDetail.setOnClickListener(showDetailListener);

        } else {
            viewHolder = (HeaderViewHolder) convertView.getTag();
        }
        Skeleton skeleton = skeletons[position];
        viewHolder.title.setText(skeleton.header);
//		viewHolder.showDetail.setTag(skeleton.header);

        return convertView;
    }

    @Override
    public long getHeaderId(int position) {
        return skeletons[position].header.hashCode();
    }

    public void setResultTvWidth(int resultTvWidth) {
        this.resultTvWidth = resultTvWidth;
    }
}
